package com.OnTimeTeam.OnTime.Alert;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import com.OnTimeTeam.OnTime.AlarmFeatures;
import com.OnTimeTeam.OnTime.AlarmSetter;
import com.OnTimeTeam.OnTime.MainActivity;
import com.OnTimeTeam.OnTime.R;
import com.OnTimeTeam.OnTime.RemindersIO;
import com.OnTimeTeam.OnTime.SmartAlarmFeatures;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyAlert2 extends Activity{

	public static boolean isAlarmOn;
	
	final Context context = this;
	CountDownTimer counter;
	private Button snoozeButton;
	private Button dismissButton;
	private TextView label;
	private Vibrator mVibrator;
	
	private Uri[] availableAlarms;
	private AudioManager mAudioManager;
    private MediaPlayer mMediaPlayer; 
    private String tuneString;
    
	private int alarmVolume;
	private int previousVolume;
	
	private boolean toSnooze;
	private Calendar currentTime;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		

        //Set Title Bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | 
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | 
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_FULLSCREEN | 
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | 
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | 
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		Log.e("Alert Called", "MyAlert2");
		
		isAlarmOn = true;
		
		//Close Main Activity
        try{MainActivity.thisActivity.finish();} catch(Exception e){}
		
		//Set Content View
        setContentView(R.layout.alertlayout_);//set the view of the first screen

        setAlertView(); //Set Alert View - Buttons and Texts
        
        currentTime = Calendar.getInstance();
        currentTime.set(Calendar.SECOND, 0);
		toSnooze = true;
		
		
		initAlertAudio();
		playSound();
		setAlertVibration(); //Set Alert Vibration

		
		counter = new CountDownTimer(50000, 1) {
	        public void onTick(long millisUntilFinished) {

	        }

	        public void onFinish() {finish();}
		};counter.start();
		

	    snoozeButton.setOnClickListener(new OnClickListener() {
	        public void onClick(final View view) {
				finish();
	        }
	    });
	    
	    dismissButton.setOnClickListener(new OnClickListener() {
	        public void onClick(final View view) {
				toSnooze = false;
				finish();
	        }
	    });	    
	}
	
	protected void initAlertAudio() {
		
		mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		
        float floatVolume = (Float.valueOf(getIntent().getExtras().getString("volume"))) / 100;
        
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
        previousVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
       
        if((floatVolume * (float)maxVolume) - (int)(floatVolume * (float)maxVolume) >= 0.5)
        	alarmVolume = (int)(floatVolume * maxVolume) + 1;
        else
        	alarmVolume = (int)(floatVolume * maxVolume);
		
		
		// set the volume to what we want it to be.  In this case it's max volume for the alarm stream.
		mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, alarmVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
		
		mMediaPlayer = new MediaPlayer();
		
		availableAlarms = getAvailableAlarms();
		
	}
	
	protected Uri[] getAvailableAlarms(){
		RingtoneManager ringtoneMgr = new RingtoneManager(this);
		ringtoneMgr.setType(RingtoneManager.TYPE_ALARM);
		Cursor alarmsCursor = ringtoneMgr.getCursor();
		int alarmsCount = alarmsCursor.getCount();
		if (alarmsCount == 0 && !alarmsCursor.moveToFirst()) {
		    return null;
		}
		Uri[] alarms = new Uri[alarmsCount+1];
		alarms[0] = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);//First is Default
		while(!alarmsCursor.isAfterLast() && alarmsCursor.moveToNext()) {
		    int currentPosition = alarmsCursor.getPosition();
		    alarms[currentPosition+1] = ringtoneMgr.getRingtoneUri(currentPosition);
		}
		return alarms;
	}
	
	protected void playSound() {
		
		

		
		//Default Tune for alarm
		Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		
		//The wanted tune
		Uri alarmSound = null;
		
		tuneString = getIntent().getExtras().getString("tune");
		if(tuneString.equals("0"))
			alarmSound = availableAlarms[0];
		else if(tuneString.equals("1"))
			alarmSound = availableAlarms[1];
		else if(tuneString.equals("2"))
			alarmSound = availableAlarms[2];
		else if(tuneString.equals("3"))
			alarmSound = availableAlarms[3];
		else if(tuneString.equals("4"))
			alarmSound = availableAlarms[4];
		else if(tuneString.equals("5"))
			alarmSound = availableAlarms[5];
		
		else {//User picked an Alarm Tune of his own!
			
			try{

				alarmSound = Uri.parse(tuneString);
				
			}catch(Exception e){
				alarmSound = ringtoneUri;
			}
			finally{
				if(alarmSound == null)
					alarmSound = ringtoneUri;
			}
		}
	
		try {
			if(!mMediaPlayer.isPlaying()){
				
            	mMediaPlayer.setDataSource(context, alarmSound);
            	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            	mMediaPlayer.setLooping(true);
            	mMediaPlayer.prepare();
            	mMediaPlayer.start();

            	mMediaPlayer.setScreenOnWhilePlaying(true);
			}
		} catch (IOException e) {
			Toast.makeText(context, "Your alarm sound was unavailable.", Toast.LENGTH_LONG).show();
		}
	}
	

	protected void setAlertView(){
		
		
		final Animation animation = new AlphaAnimation(1f, 0f); // Change alpha from fully visible to invisible
	    animation.setDuration(1000); // duration - half a second
	    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
	    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
	    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
	    
	    snoozeButton = (Button) findViewById(R.id.snoozeButton);
	    dismissButton = (Button) findViewById(R.id.dismissButton);
		label = (TextView)findViewById(R.id.label);
		label.setText(getIntent().getExtras().getString("label"));
		
	    String snoozeInterval = getIntent().getExtras().getString("snoozeInterval");
		if(snoozeInterval.equals("3"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn3Minutes));
		else if(snoozeInterval.equals("5"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn5Minutes));
		else if(snoozeInterval.equals("10"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn10Minutes));
		else if(snoozeInterval.equals("15"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn15Minutes));
		else if(snoozeInterval.equals("20"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn20Minutes));
		else if(snoozeInterval.equals("30"))
			snoozeButton.setText(getResources().getString(R.string.snooze) + "\n" + getResources().getString(R.string.fireIn30Minutes));
	    
	    snoozeButton.startAnimation(animation);
	    dismissButton.startAnimation(animation);
	}
	
	protected void setAlertVibration(){
		
		final long[] STANDARD1 = {0, 750, 750, 500, 100, 1000};
		final long[] STANDARD2 = {0, 750, 750, 500, 500, 100, 1000, 1000};
		final long[] FAST = {0, 150, 0, 150, 0, 150, 0, 150, 0};
		final long[] INTENSIVE = {0, 1000, 0, 1000, 0, 1000, 0, 1000, 0};
		final long[] BURSTS3 = {0, 200, 100, 200, 100, 200, 1000};
	    final long[] MORSE_SOS = { 0, 
	    		200, 200, 200, 200, 200, 
	    		500, 500, 200, 500, 200, 500,
	    		500, 200, 200, 200, 200, 200,
	    		1000 };	

		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		
		if(getIntent().getExtras().getString("vibration").equals("Standard I"))
			mVibrator.vibrate(STANDARD1, 0);
		else if(getIntent().getExtras().getString("vibration").equals("Standard II"))
			mVibrator.vibrate(STANDARD2, 0);
		else if(getIntent().getExtras().getString("vibration").equals("Fast"))
			mVibrator.vibrate(FAST, 0);			
		else if(getIntent().getExtras().getString("vibration").equals("Intensive"))
			mVibrator.vibrate(INTENSIVE, 0);			
		else if(getIntent().getExtras().getString("vibration").equals("3 Bursts"))
			mVibrator.vibrate(BURSTS3, 0);
		else if(getIntent().getExtras().getString("vibration").equals("Morse SOS"))
			mVibrator.vibrate(MORSE_SOS, 0);
	}
	
	protected void handleSnooze() {

		AlarmFeatures af = new AlarmFeatures();
		
		//Set Repeat for Snooze
		String snoozeRepeat = getIntent().getExtras().getString("snoozeRepeat");
		if(snoozeRepeat.equals("Unlimited"))
			af.setSnoozeRepeat("Unlimited");
		else 
			af.setSnoozeRepeat(Integer.toString((Integer.valueOf(snoozeRepeat)-1)));

		//Set Interval for the Snooze
		af.setSnoozeInterval(getIntent().getExtras().getString("snoozeInterval"));
		currentTime.add(Calendar.MINUTE, Integer.valueOf(af.getSnoozeInterval()));
		
		//Set days to repeat - the day in the next ## Mins.
		if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
			af.setDaysToRepeat("Sun");
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)
			af.setDaysToRepeat("Mon");
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY)
			af.setDaysToRepeat("Tue");
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY)
			af.setDaysToRepeat("Wed");		
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY)
			af.setDaysToRepeat("Thu");		
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
			af.setDaysToRepeat("Fri");		
		else if(currentTime.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)
			af.setDaysToRepeat("Sat");	
		
		String snoozeID = Integer.toString(AlarmSetter.createRandomAlarmID());
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
		String nextAlarmTime = sdf.format(currentTime.getTime());
		
		//change Snooze sign for the current alarm
		RemindersIO.changeSnoozeSign(getIntent().getExtras().getString("id"), 
				this.getApplicationContext().getFilesDir().getPath().toString() + "/reminders.xml", 
				snoozeID + "," + nextAlarmTime);
		
		//SET SNOOZE ID IN ## MINS
		af.setDaysIDS(snoozeID); 
		
		//HOUR & MINUTES
		af.setHour(Integer.toString(currentTime.get(Calendar.HOUR_OF_DAY)));
		af.setMinute(Integer.toString(currentTime.get(Calendar.MINUTE)));
		
		//TUNE, LABEL, VIBRATION, VOLUME, ID (of original alarm)
		af.setTune(getIntent().getExtras().getString("tune"));
		af.setLabel(getIntent().getExtras().getString("label"));
		af.setVibration(getIntent().getExtras().getString("vibration"));
		af.setVolume(getIntent().getExtras().getString("volume"));
		af.setID(getIntent().getExtras().getString("id"));
		
		
		AlarmSetter.setBackAlarm(af, getApplicationContext(), getBaseContext());

	}

    public void stopAlert(){
    	
    	//Stop Vibration
    	mVibrator.cancel();
    	
    	//Reset volume to what it was before.
        mMediaPlayer.stop();
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, previousVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

    }
    
	protected void onDestroy() {
		super.onDestroy();
		
		//Reset volume, vibration
		stopAlert();
		
		if(toSnooze)
			handleSnooze();
		else
			handleDismiss();
		
        Intent notifyService = new Intent("com.OnTimeTeam.OnTime.NotificationService");
        startService(notifyService);
		

        counter.cancel();
        
		isAlarmOn = false; 
		
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
	}
	
	//Dismiss an alarm
	private void handleDismiss() {
		
		if(!getIntent().getExtras().getString("sort").equals("Quick")) {
		
			Bundle bundle = getIntent().getExtras();
			String remindersPath = getApplicationContext().getFilesDir().getPath().toString() + "/reminders.xml";
			AlarmFeatures af = RemindersIO.getAlarm(bundle.getString("id"), remindersPath);
			
			AlarmSetter.cancelExistingAlarm(af, getApplicationContext());
			
			if(bundle.getString("sort").equals("Smart"))
				AlarmSetter.setSmartAlarm((SmartAlarmFeatures)af, getApplicationContext());
			else
				AlarmSetter.setBackAlarm(af, getApplicationContext(), getApplicationContext());
			
			RemindersIO.changeSnoozeSign(af.getID(), remindersPath, "None");
		}
	}

	protected void onPause() {
		super.onPause();
	}
	
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}


	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
	


}
